# Moths - an environment for mathy calculations
# Copyright (C) 2006 Mike Sutjipto
# Licensed under the GPL

module Moths
  
  # An environment.  Every expression must evaluated in the context
  # of an environment.  Environments mostly keep track of what functions
  # have been defined, and who their parent environment is
  class Environment
    @parent
    @defs

    # A nil parent means this is the top level
    #
    def initialize(parent = nil)
      @parent = parent
      @defs = {}
    end

    # Looks up the id, and performs a sanity check
    # i.e. makes sure the arguments match up
    #
    def resolve(id_caller)
      id = id_caller.id
      if !@defs.has_key?(id) then
        if nil == @parent then
          raise MothsError, 'Identifier not defined: ' + id.to_s
        end

        return @parent.resolve(id_caller)
      end

      defn = @defs[id]
      if defn.arg_num != id_caller.arg_num then
        raise MothsError, 'Incorrect number of arguments!'
      end

      return defn
    end

    # Add a new definition to our environment and ensure there 
    # are no name conflicts
    #
    def define(defn)
      id = defn.id.to_sym

      if @defs.has_key?(id) then
        raise MothsError, 'Identifier has already been defined!'
      end

      @defs[id] = defn
    end
  end
end
